<template>
  <div>
    <el-dialog
      :append-to-body="true"
      :title="isIdCard ? '身份证扫描' : title ? title : '其他证件'"
      :visible.sync="dialogVis"
      top="10px"
      width="1080px"
    >
      <div style="display: flex; flex-direction: row; align-items: center">
        <div style="display: flex; flex-direction: column; position: relative">
          <div
            id="ActiveXDivOne"
            :style="{
              width: previewWidth + 'px',
              height: previewHeight + 'px',
            }"
          />
          <div
            @mousedown="
              (e) => {
                {
                  draging = true
                  setStart(e)
                }
              }
            "
            @mouseup="
              (e) => {
                {
                  draging = false
                }
              }
            "
            @mousemove="
              (e) => {
                if (draging) setEnd(e)
              }
            "
            style="display: block; border: 1px green solid; position: absolute"
            :style="{
              width: previewWidth + 'px',
              height: previewHeight + 'px',
            }"
          >
            <div
              style="
                pointer-events: none;
                display: block;
                position: absolute;
                border: 1px green solid;
              "
              :style="{
                top: `${startY}px`,
                left: `${startX}px`,
                width: `${endX - startX}px`,
                height: `${endY - startY}px`,
              }"
            ></div>
          </div>

          <el-slider
            v-model="exposureValue"
            @change="changeExposure"
            :show-stops="true"
            :max="-1"
            :min="-13"
            label="亮度"
          />
          <div>预览</div>
          <div v-if="info">{{ info }}</div>
        </div>
        <div style="margin-left: 20px">
          startX {{ startX }} startY{{ startY }} endx{{ endX }} endY{{ endY }}
          <div style="display: flex; align-items: center">
            <el-image
              @click="
                () => {
                  currentPic = '正面预览'
                  toShow = 'data:;base64,' + picFront
                  showDialog = true
                }
              "
              :src="'data:;base64,' + picFront"
              style="width: 300px; height: 200px"
              fit="contain"
              id="img_front"
            />
            <el-button
              type="primary"
              style="margin-left: 20px"
              @click="tackFront"
            >
              正面
            </el-button>
          </div>
          <div
            v-if="isIdCard || hasReverse"
            style="display: flex; align-items: center; margin-top: 20px"
          >
            <el-image
              @click="
                () => {
                  currentPic = '反面预览'
                  toShow = 'data:;base64,' + picReverse
                  showDialog = true
                }
              "
              :preview-src-list="imgList"
              :src="'data:;base64,' + picReverse"
              style="width: 300px; height: 200px"
              fit="contain"
              id="img_reverse"
            />
            <el-button
              type="primary"
              style="margin-left: 20px"
              @click="tackReverse"
            >
              反面
            </el-button>
          </div>

          <div
            style="
              width: 300px;
              display: flex;
              justify-content: flex-end;
              margin-top: 20px;
            "
          >
            <el-checkbox
              style="align-self: flex-end"
              label="是复印件"
              v-model="isCopies"
            ></el-checkbox>
          </div>
          <div style="margin-top: 20px">
            <el-checkbox
              label="自动去黑边"
              v-model="replaceBorder"
            ></el-checkbox>
          </div>
          <div style="margin-top: 20px">
            阈值:{{ this.thresholdValue }}
            <el-slider
              v-model="thresholdValue"
              @change="thresholdValueChanged"
              :show-stops="true"
              :min="50"
              :max="600"
              label="黑边阈值"
            />
          </div>

          <div
            style="display: flex; justify-content: flex-end; margin-top: 20px"
          >
            <el-button size="large" type="danger" @click="dialogVis = false">
              取消
            </el-button>
            <el-button size="large" type="primary" @click="submit">
              保存
            </el-button>
          </div>
        </div>
      </div>
      <el-dialog
        :append-to-body="true"
        :title="currentPic"
        :visible.sync="showDialog"
        top="50px"
      >
        <div style="display: flex; flex-direction: column">
          <el-image
            style="width: 700px; height: 500px"
            :src="toShow"
            fit="contain"
          />
          <div
            style="display: flex; justify-content: flex-end; margin-top: 20px"
          >
            <el-button size="large" type="danger" @click="showDialog = false">
              关闭
            </el-button>
          </div>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
import { Alert } from 'element-ui'
import { title } from 'process'
import {
  StartCam,
  CaptureImage,
  CaptureImage2,
  OcxGetDeviceResolutionSecond,
  SetImagebase64,
} from '../../static/js/OcxUtil'
import {
  WsInit,
  sendMsgRefreshCam,
  sendMsgStartVideo,
  sendMsgGetResolutionSecond,
  sendMsgCaptureSecond,
  sendMsgCapture,
  sendMsgShotBase64,
  sendMsgCloseVideo,
  sendMsgZoom,
  sendMsgSetAutoExposure,
  sendMsgSetExposure,
  sendMsgGetExposureRange,
} from '../../static/js/WsUtil'
let isIE = false
var isSecondDev = false //是否有两个canvas显示视频
var camidMain = -1 //主头ID
var camidSub = 0 //副头ID
export default {
  //参数
  props: [
    'value', //bool 是否显示组件
    'isIdCard', //是否身份证
    'title', //标题，如驾驶证
    'hasReverse', //是否有反面,
  ],
  //事件
  emits: [
    'onSave', //保存，返回{ picFront: 【正面】, picReverse: 【反面】,isCopies:【bool是否复印件】,}
    'onCancle', //点取消按钮
  ],
  data: function () {
    return {
      debugMode: false, //显示测试图片
      cameraLoaded: false,
      picFront: '',
      picReverse: '',
      cutted: '',
      isReverse: false,
      toShow: null,
      showDialog: false,
      exposureValue: -3,
      currentPic: '',
      info: '正在初始化',
      startX: 216,
      startY: 181,
      endX: 382,
      endY: 285,
      previewWidth: 600,
      previewHeight: 448,
      // previewWidth: 1600,
      //previewHeight: 1200,
      draging: false,
      isCopies: false,
      replaceBorder: true,
      thresholdValue: 550,
      dialogVis: false,
    }
  },
  computed: {
    imgList: function () {
      var imgs = []
      if (this.picFront) {
        imgs.push('data:;base64,' + this.picFront)
      }
      if (this.picReverse) {
        imgs.push('data:;base64,' + this.picReverse)
      }
    },
  },
  watch: {
    value: function () {
      this.dialogVis = this.value
    },
    dialogVis: function () {
      this.$emit('update:value', this.dialogVis)
      if (this.dialogVis && !this.cameraLoaded) {
        this.$nextTick(() => {
          this.initCamera()
        })
      }
      if (this.dialogVis) {
        this.thresholdValue = parseInt(localStorage.getItem('threshold'))
        if (this.isIdCard) {
          this.startX = localStorage.getItem('startX')
          this.startY = localStorage.getItem('startY')
          this.endX = localStorage.getItem('endX')
          this.endY = localStorage.getItem('endY')
        }
      }
    },

    startX: function () {
      if (this.isIdCard) localStorage.setItem('startX', this.startX)
    },
    startY: function () {
      if (this.isIdCard) localStorage.setItem('startY', this.startY)
    },
    endX: function () {
      if (this.isIdCard) localStorage.setItem('endX', this.endX)
    },
    endY: function () {
      if (this.isIdCard) localStorage.setItem('endY', this.endY)
    },
  },
  destroyed: function () {
    console.log('关闭设备')
    try {
      sendMsgCloseVideo()
    } catch (ex) {}
  },
  methods: {
    getCanves() {
      let canvas = document.getElementById('cameraCanvas')
      let cxt = canvas.getContext('2d')
    },
    submit() {
      if (!this.picFront) {
        this.$message('请扫描正面图片')
        return
      }
      if ((this.isIdCard || this.hasReverse) && !this.picReverse) {
        this.$message('请扫描反面图片')
        return
      }
      this.$confirm(
        `保存 ${
          this.isIdCard ? '身份证' : this.title ? this.title : '其他证件'
        } 【 ${this.isCopies ? '复印件' : '原件'}】扫描件？`,
        '注意',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          this.$emit('onSave', {
            picFront: this.picFront,
            picReverse: this.picReverse,
            isCopies: this.isCopies,
          })
        })
        .catch((ex) => {
          console.log(ex)
        })
    },

    changeExposure() {
      if (this.dialogVis) {
        console.log('change', this.exposureValue)
        sendMsgSetAutoExposure(1)
        setTimeout(() => {
          sendMsgSetExposure(this.exposureValue)
        }, 500)
      }
    },
    addExposure(val) {
      this.exposureValue += val
    },
    exposureDecrease() {},
    tackFront() {
      this.isReverse = false
      this.doTackPhoto()
    },
    tackReverse() {
      this.isReverse = true
      this.doTackPhoto()
    },
    initCamera() {
      //if (navigator.userAgent.indexOf('MSIE') >= 0) {
      isIE = false
      if (!window.WebSocket) {
        alert('浏览器不支持摄像头通信，请使用谷歌浏览器')
      }
      let width = this.previewWidth + 'px'
      let heigt = this.previewHeight + 'px'
      let html = `<canvas id="cameraCanvas" width="${width}" height="${heigt}" style="border:1px solid #d3d3d3;">`
      //其他浏览器加载控件
      document.getElementById('ActiveXDivOne').innerHTML = html
      if (this.debugMode) {
        var can = document.getElementById('cameraCanvas')
        var ctx = can.getContext('2d')
        var img = new Image()
        img.setAttribute('style', 'object-fit:contain')
        img.onload = function () {
          ctx.drawImage(img, 0, 0, 1600, 1200, 0, 0, 1600, 1200)
        }
        img.src = require('@/assets/j16001200.png')
      }
      try {
        WsInit(
          500,
          400,
          500,
          400,
          true,
          false,
          (r, e) => {
            if (r == 164 || r == 163) {
              this.$message({
                message: '连接扫描仪失败，请检查驱动是否正常启动',
                type: 'error',
              })
            }
          },
          (r, e) => {},
          (r, e) => {
            this.$nextTick(() => {
              this.StartCam()
              setTimeout(() => {
                sendMsgSetAutoExposure(1)
                sendMsgShotBase64(1)
                sendMsgSetExposure(this.exposureValue)
                sendMsgGetExposureRange()
                sendMsgZoom(1)
              }, 500)
            })
          },
          this.GetDevName,
          this.InfoTextCallback,
          (c) => {
            camidMain = c
          }
        )
      } catch (ex) {
        console.log('初始化失败')
      }
    },
    StartCam() {
      try {
        sendMsgStartVideo(camidMain, 1600, 1200)
        //StartCam(0,1600,1200,sendMsgRefreshCam,sendMsgStartVideo);
      } catch (ex) {}
    },
    doTackPhoto() {
      var type = 0
      this.debugMode
        ? this.ClippingImage('', 1, (r) => {
            r = r.replace('data:image/png;base64,', '')
            this.isReverse ? (this.picReverse = r) : (this.picFront = r)
          })
        : CaptureImage(type, sendMsgCapture)
    },
    GetDevName(num, strUsbNamr) {
      if (isSecondDev) {
        if (num > 1) {
          OcxGetDeviceResolutionSecond(sendMsgGetResolutionSecond)
        }
      }
    },
    zoomIn() {
      sendMsgZoom(0)
    },
    zoomOut() {
      sendMsgZoom(1)
    },
    dataURLtoFile(dataurl, filename = 'file') {
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let suffix = mime.split('/')[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime,
      })
    },
    ClippingImage1(base64Codes, width, height, quality, callback) {
      var img = new Image()
      img.src = base64Codes

      if (this.debugMode) {
        width = (width / this.previewWidth) * 1600
        height = (height / this.previewHeight) * 1200
      }

      //生成canvas
      var canvas = document.createElement('canvas')
      var ctx = canvas.getContext('2d')
      var createw = document.createAttribute('width')
      var createh = document.createAttribute('height')
      let startX
      let startY
      if (this.debugMode) {
        startX = (this.previewWidth - width) / 2 + 10
        startY = (this.previewHeight - height) / 2
      } else {
        startX = (1600 - width) / 2 + 10
        startY = (1200 - height) / 2
      }
      createw.nodeValue = width
      createh.nodeValue = height
      canvas.setAttributeNode(createh)
      canvas.setAttributeNode(createw)
      img.onload = function () {
        ctx.drawImage(img, startX, startY, width, height, 0, 0, width, height)
        var base64Result = canvas.toDataURL('image/png', quality)
        callback(base64Result)
      }
      img.src = base64Codes
    },
    ClippingImage(base64Codes, quality, callback) {
      var img = new Image()
      //img.src = base64Codes
      let width
      let height

      if (this.debugMode) {
        width = this.endX - this.startX

        height = this.endY - this.startY
      } else {
        width = ((this.endX - this.startX) / this.previewWidth) * 1600
        height = ((this.endY - this.startY) / this.previewHeight) * 1200
      }

      //生成canvas
      var canvas = document.createElement('canvas')
      var ctx = canvas.getContext('2d')
      var createw = document.createAttribute('width')
      var createh = document.createAttribute('height')
      let startX
      let startY
      if (this.debugMode) {
        startX = this.startX
        startY = this.startY
      } else {
        startX = (this.startX / this.previewWidth) * 1600
        startY = (this.startY / this.previewHeight) * 1200
      }

      createw.nodeValue = width
      createh.nodeValue = height
      canvas.setAttributeNode(createh)
      canvas.setAttributeNode(createw)

      img.onload = () => {
        ctx.drawImage(img, startX, startY, width, height, 0, 0, width, height)
        var data = ctx.getImageData(0, 0, width, height)
        if (this.replaceBorder) {
          for (let r = 0; r < data.height; r++) {
            for (let c = 0; c < data.width; c++) {
              if (!this.isInEdge(data.data, r, c, data.width)) {
                break
              } else {
                let st = (r * data.width + c) * 4
                data.data[st] = 255
                data.data[st + 1] = 255
                data.data[st + 2] = 255
              }
            }
          }
          for (let r = 0; r < data.height; r++) {
            for (let c = data.width - 1; c > 0; c--) {
              if (!this.isInEdge(data.data, r, c, data.width)) {
                break
              } else {
                let st = (r * data.width + c) * 4
                data.data[st] = 255
                data.data[st + 1] = 255
                data.data[st + 2] = 255
              }
            }
          }
        }

        //for (let i = 0; i < data.data.length; i += 4) {
        //  if (data.data[i] + data.data[i + 1] + data.data[i + 2] < 150) {
        //    data.data[i] = 1;
        //    data.data[i + 1] = 1;
        //    data.data[i + 2] = 255;
        //    data.data[i + 3] = 255;
        //  }
        //
        //
        //}
        ctx.putImageData(data, 0, 0)
        var base64Result = canvas.toDataURL('image/png', quality)
        callback(base64Result)
      }
      img.src = this.debugMode ? require('@/assets/j16001200.png') : base64Codes
    },
    isInEdge(data, row, col, width, edgeFlex = 3) {
      let graydeg = this.thresholdValue
      let st = (row * width + col) * 4
      let st2 = st + edgeFlex
      if (data[st] + data[st + 1] + data[st + 2] < graydeg) {
        let av = (data[st] + data[st + 1] + data[st + 2]) / 3
        return (
          Math.abs(data[st] - av) < 50 &&
          Math.abs(data[st + 1] - av) < 50 &&
          Math.abs(data[st + 2] - av) < 50
        )
        // data[st] = 255;
        // data[st + 1] = 255
        // data[st + 2] = 255
      }
      return false
    },
    InfoTextCallback(type, str) {
      var text = ''
      if (type == 0) {
        text = '图片路径:' + str + '\r\n'
      } else if (type == 1) {
        text = '默认路径:    ' + str + '\r\n'
      } else if (type == 2) {
        text = '条码:    ' + str + '\r\n'
      } else if (type == 3) {
        text = '文件上传服务器成功:' + str + '\r\n'
      } else if (type == 4) {
        text = '文件上传服务器失败:' + str + '\r\n'
      } else if (type == 5) {
        text = '扫描完成\r\n'
        // text ="data:;base64," +str+"\r\n";
        this.ClippingImage('data:;base64,' + str, 1, (r) => {
          r = r.replace('data:image/png;base64,', '')
          this.isReverse ? (this.picReverse = r) : (this.picFront = r)
        })
        //imgBase64Upload = str;
      } else if (type == 6) {
        text = '删除文件成功:' + str + '\r\n'
      } else if (type == 7) {
        text = '二维码:' + str + '\r\n'
      } else if (type == 8) {
        text = '拍照失败:' + str + '\r\n'
      } else if (type == 9) {
        text = '身份证名字:' + str + '\r\n'
      } else if (type == 10) {
        text = '身份证:' + str + '\r\n'
      } else if (type == 11) {
        text = '身份证性别:' + str + '\r\n'
      } else if (type == 12) {
        text = '身份证民族:' + str + '\r\n'
      } else if (type == 13) {
        text = '身份证生日:' + str + '\r\n'
      } else if (type == 14) {
        text = '身份证地址:' + str + '\r\n'
      } else if (type == 15) {
        text = '身份证签发机关:' + str + '\r\n'
      } else if (type == 16) {
        text = '身份证有效开始日期:' + str + '\r\n'
      } else if (type == 17) {
        text = '身份证有效截至日期:' + str + '\r\n'
      } else if (type == 18) {
        text = '安全模块号:' + str + '\r\n'
      } else if (type == 19) {
        //身份证头像
        text = '身份证头像base64\r\n'
        var imgobj1 = document.getElementById('img1')
        imgobj1.src = 'data:;base64,' + str

        imgBase64Upload = str
      } else if (type == 21) {
        text = 'base64编码成功,请自行处理str(副头)\r\n'
        //text ="data:;base64," +str+"\r\n";
        //var imgobj1 = document.getElementById("img2");
        //  imgobj1.src = "data:;base64," + str;

        //  imgBase64Upload = str;
      } else if (type == 22) {
        this.cameraLoaded = true
        text = '曝光范围:' + str + '\r\n'
      } else if (type == 23) {
        text = '亮度范围:' + str + '\r\n'
      } else if (type == 24) {
        text = '上传服务器返回:' + str + '\r\n'
      } else if (type == 25) {
        var imgobj1 = document.getElementById('img1')
        imgobj1.src = 'data:;base64,' + str

        text = '身份证复印件' + '\r\n'
      } else if (type == 26) {
        text = '当前设备数量:' + str + '\r\n'
      } else if (type == 27) {
        text = '麦克风:' + str + '\r\n'
      } else if (type == 28) {
        text = '人脸抓拍base64编码成功,请自行处理str\r\n'
        // text ="data:;base64," +str+"\r\n";
        var imgobj1 = document.getElementById('img1')
        imgobj1.src = 'data:;base64,' + str
      } else if (type == 29) {
        var strTmp = str.split('D')
        text =
          '银行卡号:' + strTmp[0] + '---有效日期(年月):' + strTmp[1] + '\r\n'
      } else if (type == 30) {
        text = '人脸抓拍base64编码成功,请自行处理str\r\n'
        // text ="data:;base64," +str+"\r\n";
        var imgobj1 = document.getElementById('img2')
        imgobj1.src = 'data:;base64,' + str

        imgBase64Upload = str
      } else if (type == 33) {
        fingerBase64 = str
        text = '指纹:' + str + '\r\n'
      } else if (type == 34) {
        fingerLen = str
        text = '指纹长度:' + str + '\r\n'
      } else if (type == 36) {
        var imgobj1 = document.getElementById('img1')
        imgobj1.src = 'data:;base64,' + str
        text = '指纹图片base64\r\n'
      } else if (type == 37) {
        text = '指纹对比成功 id:' + str + '\r\n'
      } else if (type == 43) {
        // text = "所有设备VidPid:"+str+"\r\n";

        var allMessage = new Array()
        allMessage = str.split('**')
        var num = allMessage[0]
        if (num > 0) {
          for (var i = 0; i < num; i++) {
            if (camidMain == i) {
              text = text + '主头'
            } else if (camidSub == i) {
              text = text + '副头'
            }

            text = text + allMessage[i + 1] + '\r\n'
          }
        } else text = '未发现设备\r\n'
      } else if (type == 46) {
        text = '信息:' + str + '\r\n'
      } else if (type == 164 || type == 163) {
        text = '信息:扫描服务未启动，请检查驱动程序是否安装'
      }
      this.info = text
    },
    printInfo(str, e) {},
    setStart(e) {
      this.startX = e.layerX
      this.startY = e.layerY
      this.endX = e.layerX + 1
      this.endY = e.layerY + 1
    },
    setEnd(e) {
      this.endX = e.layerX
      this.endY = e.layerY
    },
    thresholdValueChanged(v) {
      localStorage.setItem('threshold', v)
    },
  },
}
</script>
